<template>
  <el-dialog title="图片管理" width="640px" class="icon-dialog" :visible.sync="imagesDiaShow" @open="open" :before-close="closePickForm" append-to-body>
      <div style="padding-left:10px">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-upload class="upload-demo" ref="upload" multiple action="#" :before-upload="beforeUpload" :http-request="upload">
              <el-button class="el-icon-upload" size="small" type="primary"> 上传图片</el-button>
            </el-upload>
          </el-col>
          <el-col :span="8">
            <el-button class="el-icon-delete" size="small" type="danger" @click="deletePic">批量删除</el-button>
          </el-col>
        </el-row>
        <el-row style="margin-top:15px;">
          <el-col :span="24">
            <el-row>
              <div class="image-wrap"  v-for="(item,index) in list" :key="index" @click="selection(item.filepath)">
                <label v-for="(v, k) in files" :key="k" v-show="item.filepath === v">
                  <input type="checkbox" :checked="item.filepath === v">
                  <i>✓</i>
                </label>
                <div class="imgStyle">
                  <img :src="item.filepath" /><br/>
                </div>
              </div>
            </el-row>
            <Page :total="page_data.total" :page.sync="page_data.page" :limit.sync="page_data.limit" @pagination="index" />
          </el-col>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" :loading="loading" type="primary" @click="submitPick" >
          <span>确 定</span>
        </el-button>
        <el-button size="small" @click="closePickForm">取 消</el-button>
      </div>
    </el-dialog>
</template>

<script>
import Page from '@/components/common/Page.vue'
export default {
	components: {
		Page,
	},
  	props: {
		imagesDiaShow: {
			type: Boolean,
			default: false
		},
	},
	watch: {
		imagesDiaShow(value) {
			if(value){
				this.index()
			}
		}
	},
	data() {
		return {
			files: [],
			list: [],
			loading: false,
			progressPercent:0,
			progress:false,
			page_data: {
				limit: 20,
				page: 1,
				total:20,
			},
		}
	},
	methods:{
		open(){
			this.files = []
		},
		beforeUpload(item){
			if(item.type.split('/')[0] !== 'image') {
				this.$message.error('请选择图片')
				return false
			}
		},
		selection(filepath){
			let index = this.files.indexOf(filepath)
			if (index === -1) {
				this.files.push(filepath)
			}else {
				this.files.splice(index, 1)
			}
		},
		deletePic(){
			this.$confirm('是否删除文件?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$axios.post('/admin/Base/deleteFile',{filepath:this.files}).then(res => {
					if(res.data.status == 200){
						this.$message({message: '删除成功', type: 'success'})
						this.index()
					}else{
						this.$message.error(res.data.msg)
					}
				})
			})
		},
		upload(item){
			let formdata = new FormData()
			let ali = new FormData()  //此处非常坑 阿里上传file属性必须要放到最后  所以只能赋值对象
			formdata.append('file', item.file)
			const config = {
				onUploadProgress: progressEvent => {
					if (progressEvent.lengthComputable) {
						this.progress = true
						this.progressPercent = Number((progressEvent.loaded / progressEvent.total * 100).toFixed(2))
					}
				}
			}
			try {
				this.$axios.post('/admin/Upload/upload', formdata,config).then(res => {
					if(res.data.status == 200){
						if(!res.data.filestatus){
							if(res.data.data.type == 'qiniuyun'){
								formdata.append('token',res.data.data.token)
								formdata.append('key',res.data.data.key)
								axios.post(res.data.data.serverurl, formdata,config).then(ret => {
									if(ret.data.key){
										this.$axios.post('/admin/Upload/createFile',{filepath:res.data.data.domain+'/'+ret.data.key}).then(res => {
											this.progressPercent = 0
											this.progress = false
											this.index()
										})
									}
								})
							}else if(res.data.data.type == 'tencent'){
								let vm = this
								$.getScript("/assets/js/cos-js-sdk-v5.min.js",function(script){
									var cos = new COS({
										SecretId: res.data.data.SecretId,
										SecretKey: res.data.data.SecretKey
									});
									cos.putObject({
										Bucket: res.data.data.Bucket, // 桶名-APPID  必须
										Region: res.data.data.Region, //区域 必须
										Schema: res.data.data.Schema, //区域 必须
										Key: res.data.data.key, //文件名必须 
										Body: item.file, // 上传文件对象
										onProgress: function (progressData) {
										}
									}, function (err, data) {
										if(data.Location){
											const url = res.data.data.Schema+'://'+data.Location
											this.$axios.post('/admin/Upload/createFile',{filepath:url}).then(result => {
												vm.setFilePath(item,url)
											})
										}
									})
								})
							}else if(res.data.data.type == 'ali'){
								ali.append('Signature',res.data.data.sign)
								ali.append('callback',res.data.data.callback)
								ali.append('OSSAccessKeyId',res.data.data.OSSAccessKeyId)
								ali.append('policy',res.data.data.policy)
								ali.append('key',res.data.data.key)
								ali.append('file', item.file)
								axios.post(res.data.data.serverurl, ali,config).then(ret => {
									if(ret.data.code == 1){
										this.$axios.post('/admin/Upload/createFile',{filepath:ret.data.data}).then(res => {
											this.progressPercent = 0
											this.progress = false
											this.index()
										})
									}
								})
							}else{
								this.$message({message: '上传成功', type: 'success'})
								this.progressPercent = 0
								this.progress = false
								this.index()
							}
						}else{
							this.$message.error('文件已经存在')
						}
					}
				})
			}catch (error) {
				this.$message.error('上传失败')
			}finally {
				this.$refs.upload && this.$refs.upload.clearFiles()
			}
		},
		index(){
			let param = {limit:this.page_data.limit,page:this.page_data.page}
			this.loading = true
			this.$axios.post('/admin/Base/fileList',param).then(res => {
				this.list = res.data.data.data
				this.page_data.total = res.data.data.total
				this.loading = false
			})
		},
		submitPick(){
			if(this.files[0] !== undefined){
				this.$emit('update:siglepic',this.files[0])
			}
			this.closePickForm()
		},
		closePickForm(){
			this.$emit('update:imagesDiaShow', false)
		}
	}
}
</script>

<style lang="scss" scoped>
.image-wrap {
    position: relative;
    display: inline-block;
    box-sizing: content-box;
    margin: 10px 15px 0 0;
    vertical-align: top;
    &:hover {
      .icon-wrap {
        opacity: 1;
      }
    }
    .imgStyle img{
      width:100px;
      height: 100px;
      border: 1px solid #d9d9d9;
      border-radius: 6px;
    }
    .icon-wrap {
      position: absolute;
      left: 0;
      border-radius: 6px;
      width: 102px;
      height: 102px;
      cursor: default;
      text-align: center;
      line-height: 100px;
      color: #fff;
      opacity: 0;
      font-size: 20px;
      background-color: rgba(0, 0, 0, .7);
      transition: opacity .3s;
      .el-icon-zoom-in {
        cursor: pointer;
        margin-right: 8px;
      }
      .el-icon-delete {
        cursor: pointer;
      }
    }
}
label {
 font-size: 25px;
 cursor: pointer;
 position: absolute;
 top: -2px;
 right: 0px;
 z-index: 150;
}
 
label i {
 font-size: 15px;
 font-style: normal;
 display: inline-block;
 width: 18px;
 height: 18px;
 text-align: center;
 line-height: 18px;
 color: #fff;
 vertical-align: middle;
 margin: -3px 0px 1px 0px;
}
 
input[type="checkbox"],
input[type="radio"] {
 display: none;
 outline: none;
}
 
input[type="radio"]+i {
 border-radius: 7px;
}
 
input[type="checkbox"]:checked+i,
input[type="radio"]:checked+i {
 background: #67c23a;
 color: #FFF;
}
@import '@/assets/scss/common.scss'
</style>